define(['moment'], function (moment) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', '$timeout', 'config',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, $timeout, config) {

            // 可用工具清單
            $scope.item_list = [
                // 錫膏
                {
                    name: 'solder_paste',
                    code: '0',
                    title: $filter('translate')('SMT07.title_solder_paste'),
                    parameter_value:'SMTAPAMag',
                    icon: 'bookmark',
                    status: [
                        {name:'use', code:'10', status:'1'}, // 領用
                        {name:'reheat_start', code:'20', status:''},  // 回溫開始
                        {name:'reheat_end', code:'30', status:''},    // 回溫結束
                        {name:'return', code:'0', status:'1'}, // 歸還
                        {name:'revoke', code:'80', status:''} // 報廢
                    ]
                },
                // 紅膠
                {
                    name: 'red_glue',
                    code: '3',
                    title: $filter('translate')('SMT07.title_red_glue'),
                    parameter_value:'SMTAPAMag',
                    icon: 'bookmark',
                    status: [
                        {name:'use', code:'10', status:'1'}, // 領用
                        {name:'reheat_start', code:'20', status:''},  // 回溫開始
                        {name:'reheat_end', code:'30', status:''},    // 回溫結束
                        {name:'return', code:'0', status:'1'}, // 歸還
                        {name:'revoke', code:'80', status:''} // 報廢
                    ]
                },
                // 網板
                {
                    name: 'stencil',
                    code: '1',
                    title: $filter('translate')('SMT07.title_stencil'),
                    parameter_value:'SMTSQMag',
                    icon: 'bookmark',
                    status: [
                        {name:'use', code:'10', status:'1'}, // 領用
                        {name:'wash_start', code:'21', status:''}, // 清洗開始
                        {name:'wash_end', code:'31', status:''}, // 清洗結束
                        {name:'return', code:'0', status:'1'}, // 歸還
                        {name:'revoke', code:'80', status:''} // 報廢
                    ]
                },
                // 刮刀
                {
                    name: 'scraper',
                    code: '2',
                    title: $filter('translate')('SMT07.title_scraper'),
                    parameter_value:'SMTSQMag',
                    icon: 'bookmark',
                    status: [
                        {name:'use', code:'10', status:'1'}, // 領用
                        {name:'wash_start', code:'21', status:''}, // 清洗開始
                        {name:'wash_end', code:'31', status:''}, // 清洗結束
                        {name:'return', code:'0', status:'1'}, // 歸還
                        {name:'revoke', code:'80', status:''} // 報廢
                    ]
                },
                // 其他
                {
                    name: 'other',
                    code: '4',
                    title: $filter('translate')('SMT07.title_other'),
                    parameter_value:'SMTXMag',
                    icon: 'bookmark',
                    status: [
                        {name:'use', code:'10', status:'1'}, // 領用
                        {name:'wash_start', code:'21', status:''}, // 清洗開始
                        {name:'wash_end', code:'31', status:''}, // 清洗結束
                        {name:'return', code:'0', status:'1'}, // 歸還
                        {name:'revoke', code:'80', status:''} // 報廢
                    ]
                }
            ];

            $scope.init = function(){
                $scope.user_name = config.cache.name;
                $scope.envInfo = $filter('translate')('Login.env.'+config.setting.environment);
                $scope.mode = '';
                $scope.now_item = {title:''};
                $scope.result = [];
                $scope.exe_result = [];
                $scope.queue_list = [];//錫膏、紅膠先進先出表
                $scope.toolControl = config.cache.sys_parameter['SMTInfo.SMTMToolControl'];
            
                 // 自動隱蔽鍵盤
                 element_barcode_no = document.getElementById('input_barcode');
                 makeBarcodeInput(element_barcode_no);
                 element_barcode_no.focus();
            };

            $scope.back = function(){
                if($scope.mode == ''){
                    $scope.$root.hideMenu();
                    $scope.$root.changeProgram('menu', true);
                } else {
                    if($scope.result && $scope.result.length > 0){
                        $scope.$root.showConfirm($filter('translate')('SMT07.msg.leave_but-data-disappear'),function(dialog){
                            dialog.hide();
                            $scope.mode = '';
                            $scope.now_item = {title:''};
                            $scope.result = [];
                            $scope.exe_result = [];
                            $scope.queue_list = [];//清掉紅膠錫膏對照表對照表
                        });
                    } else {
                        $scope.mode = '';
                        $scope.now_item = {title:''};
                        $scope.result = [];
                        $scope.exe_result = [];
                        $scope.queue_list = [];//清掉紅膠錫膏對照表對照表
                    }
                }
            };

            // 選擇工具
            $scope.selectTool = function(item){
                if(item.code == '0' || item.code == '3' && $scope.toolControl=='1'){
                    tool_orderby_info_get(item.code);
                }

                sys_parameter_info_get(item.parameter_value, function(result){
                    $scope.mode = 'select-tool';
                    $scope.now_item = item;
                    $scope.now_item.now_status = [];
                    item.status.forEach(function(status){
                        if(status.status == '' || status.status == result){
                            $scope.now_item.now_status.push(status);
                            $scope.now_process_name = $scope.now_item.now_status[0].name;
                            $scope.now_process_code = $scope.now_item.now_status[0].code;
                        }
                    });
                    // 重新進入都預設在領用步驟
                    $scope.now_item.now_process = $scope.now_item.now_status[0].code;
                });
            };

            function tool_orderby_info_get(code,callback){
                let content = {
                    tool_class:code
                }
                $MMWService.sendToServer({
                    uri : 'ServicesSMT.Module_SMT.tool_orderby_info_get',
                    content : content,
                    success : function(data){
                        $scope.queue_list = data;
                        $scope.queue_list.forEach((item,key)=>{
                            item.mark = false;
                            item.seq = key;
                        })
                    }
                });
            }

            //QRCode輸入
            $scope.QRCodeScanner = function(){
                $scope.$root.OpenScanner({
                    after : function(result){
                        input_barcode_no_callback(result.text);
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    },
                    orientation : 'portrait'
                });
            };

            //barcode輸入
            $scope.input_barcode = function(barcode){
                input_barcode_no_callback(barcode);
            };

            // 選擇主要流程 select_mainProcess
            //$scope.mode = {mainProcess_mode : 'A'};
            //var isData = false;
            $scope.SelectProcess = function(status_item){
                $scope.queue_list.forEach(function(item){//換流程時，對照表上的所有標記歸零
                    item.mark=false;
                });
                $scope.now_process_name = status_item.name;
                $scope.now_process_code = status_item.code;
                if($scope.result && $scope.result.length > 0){
                    $scope.$root.showConfirm($filter('translate')('SMT07.msg.aready_have_result'), function(confirm_dialog){
                        confirm_dialog.hide();
                        $scope.now_process_name = status_item.name;
                        $scope.now_item.now_process = status_item.code;
                        $scope.confirm();
                    },function(cancelDialog){
                        cancelDialog.hide();
                        // 取消就保留在原本的步驟。
                        $scope.now_process_name = $scope.result[0].now_process_name;
                    });
                } else {
                    $scope.result = [];
                    $scope.now_item.now_process = status_item.code;
                }
            }

            $scope.RemoveResult = function(item){
                if($scope.queue_list.length != 0){//清除$scope.result中 item.seq ~ 0的項目
                    $scope.result = $scope.result.filter(this__item => (this__item.seq < item.seq));
                    $scope.queue_list.forEach(this__item => {//資料表中的可刷入清單調整
                        if(this__item.seq >= item.seq){
                            this__item.mark = false;
                        }
                    })
                }else{
                    $scope.result.splice($scope.result.indexOf(item), 1);
                }
            }

            // 歸還步驟 - 如果後台回傳 [超過開封時間(狀態S)] 訊息時，會出現報廢小按鈕
            $scope.revoke = function(item){
                var content = {
                    tool_details: [{
                        tool_type: item.tool_type,
                        tool_no:item.tool_no,
                        status:'N',
                        tool_handle_type: '80', // 80報廢
                        result:$filter('translate')('SMT07.unhandle'),
                        order:new Date(),
                        now_process_name: 'revoke'
                    }]
                };
                tool_handle_set_process(content, function(data){
                    $scope.$root.showToast($filter('translate')('common.msg.success'));
                    if(data && data.length > 0){
                        $scope.exe_result.unshift(data[0]);
                        item.revokeSuccess = true;
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });    
            };

            // 執行主要項目 start_mainItem
            $scope.confirm = function(){
                var content = {
                    tool_details:$scope.result
                };
                tool_handle_set_process(content, function(data){
                    $scope.result.length = 0;
                    if(data && data.length > 0){
                        var msg = '';
                        for(var i = 0; i < data.length; i++){
                            $scope.exe_result.unshift(data[i]);      
                            if($scope.now_process_name == 'return' && data[i].status == 'S') 
                            {
                                // 歸還步驟 → 如果後台回傳 [超過開封時間(狀態S)] 訊息時，另外跳提示訊息
                                msg += '<label style="display: block; padding: 3px 0;">' + data[i].tool_no + ' : ' + data[i].result
                                       + $filter('translate')('SMT07.msg.please_execute_revoke') + '</label>';     
                            }   
                        };
                        if(msg == '')
                            $scope.$root.showToast($filter('translate')('common.msg.success'));
                        else
                            $scope.$root.showToast(msg);
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });    
            };

            function tool_list_process(barcode){
                var filter_result = $filter('filter')($scope.result, {tool_no: barcode, now_process_name: $scope.now_process_name});
                var filter_exe_result = $filter('filter')($scope.exe_result, {tool_no: barcode, now_process_name: $scope.now_process_name});
                var isSuccess = false;
                if(barcode!=''){
                    for(var i = 0; i < filter_exe_result.length; i++){
                        // 後端回傳狀態E或S(畫面上紅字)，不卡控
                        if(filter_exe_result[i].status == 'E' || filter_exe_result[i].status == 'S')
                            isSuccess = false;
                        // 執行完成，卡控不能再次輸入工具
                        else
                        {
                            isSuccess = true;
                            break;
                        }    
                    };
                    // 同個步驟不能刷入已經存在或已完成的工具編號
                    if(filter_result.length > 0)
                        $scope.$root.showAlert($filter('translate')('SMT07.msg.can_not_brush_same_tool'));
                    // 此工具已執行完成，無法再次刷入
                    else if(isSuccess)
                        $scope.$root.showAlert($filter('translate')('SMT07.msg.can_not_brush_again'));
                    else
                    {
                        $scope.result.push({
                            tool_type:$scope.now_item.code,
                            tool_no:barcode,
                            status:'N',
                            tool_handle_type:$scope.now_item.now_process,
                            result:$filter('translate')('SMT07.unhandle'),
                            order:new Date(),
                            now_process_name: $scope.now_process_name,
                            seq:right_tool_key//紀錄此工具在資料表第幾筆
                        });
                        if($scope.queue_list.length != 0){
                            $scope.queue_list[right_tool_key].mark = true;
                        }
                        $scope.result_copy = angular.copy($scope.result);
                    }
                }
            }

            let right_tool_key;
            // barcode輸入 callback
            function input_barcode_no_callback(barcode){
                if($scope.queue_list.length != 0 && $scope.toolControl=='1'){//如果有取得對照表，則進入比對程序
                    if($scope.now_process_code =='10'){//只有歸還要先進先出
                        var has__data = $scope.queue_list.some((item)=>(item.tool_no == barcode))
                        if(has__data){//資料表中有這筆資料
                            let right_tool;
                            //比較exe_result陣列中，tool_handle_type與$scope.now_item.now_process相同的資料，
                            //與$scope.queue_list相同的資料，註記上mark=true;
                            let scanned_list = $scope.exe_result.filter(function(item){
                                return item.tool_handle_type == $scope.now_item.now_process;
                            })

                            scanned_list.forEach(function(item){//已完成列表中如果有queue_list的項目，該項目標記為完成
                                $scope.queue_list.forEach(function(queue_item){
                                    if(item.tool_no == queue_item.tool_no){
                                        queue_item.mark = true;
                                    }
                                });
                            })
                            //對照表格查出此時該用哪個tool_no
                            for(let i = 0;i<$scope.queue_list.length;i++){
                                let item = $scope.queue_list[i];
                                if(item.mark==false){
                                    right_tool = item.tool_no;
                                    right_tool_key = item.seq;
                                    break;
                                }
                            }
                            let scanned_tool = $scope.queue_list.some(item=>(item.tool_no == barcode && item.mark== true));
                            if(barcode == right_tool){
                                tool_list_process(barcode);
                            }else if(scanned_tool){//如果此工具已用過
                                $scope.$root.showAlert($filter('translate')('SMT07.msg.tool_been_used'));
                            }else{//未照順序刷入料號
                                $scope.$root.showAlert($filter('translate')('SMT07.msg.barcode_seq_not_right') + right_tool);
                            }
                        }else{
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        }
                    }else{
                        tool_list_process(barcode);
                    }
                }else{
                    tool_list_process(barcode);
                }
            };

            function sys_parameter_info_get(tool_type, callback){
                $MMWService.pageNumberInfoGet({
                    page_mode : 'sys_parameter_info_get',
                    query_condition_info:[
                        {column_name:'PARAMETERTYPE', query_mode:'0', value: 'SMTInfo', merge_condition_model:'AND'},
                        {column_name:'PARAMETERNO', query_mode:'0', value: tool_type, merge_condition_model:'AND'}
                    ]
                }, function(itemList){
                    if(itemList && itemList.length > 0 ){
                        callback(itemList[0].parameter_value);
                    } else {
                        callback('N');
                    }
                });
            }

            function tool_handle_set_process(content, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSMT.Module_SMT.tool_handle_set_process',
                    content : content,
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            }

            $scope.input_PDA_barcode = function(event){
                if (event.keyCode == 13) {
                    element_barcode_no.blur();
                    input_barcode_no_callback($scope.barcode)
                    $scope.barcode = '';
                } else {
                    $scope.barcode = $scope.barcode || '';
                }
            }

            //20200914 modify by Dustdusk for M#: 增加
            function makeBarcodeInput(el) {
                var _input = el.getElementsByClassName('barcode_input')[0];
                //var _mask = el.getElementsByClassName('barcode_mask')[0];
                el.focus = function () {
                    //e.preventDefault();
                    //_mask.click();
                    el.click();
                }
                el.addEventListener('click', function (e) {
                    e.preventDefault();
                    //_input.value = '';
                    if (document.activeElement !== _input)
                        _input.focus();
                });
                _input.addEventListener('focus', function (e) {
                    e.preventDefault();
                    setTimeout(function () {
                        _input.removeAttribute('readonly');
                    }, 200);
                });
                _input.addEventListener('blur', function (e) {
                    e.preventDefault();
                    _input.setAttribute('readonly', 'readonly');
                });
            }
    }];
});
